package com.zxr.demo.service.impl;
import com.zxr.demo.commom.bo.AddUserBO;
import com.zxr.demo.commom.bo.LoginBO;
import com.zxr.demo.commom.vo.UserVO;
import com.zxr.demo.model.Users;
import com.zxr.demo.repository.UsersRepository;
import com.zxr.demo.service.UserService;
import com.zxr.demo.utils.JwtUtil;
import org.redisson.api.RList;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    UsersRepository usersRepository;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Boolean addUser(AddUserBO addUserBO) {
        Users user = new Users();
        user.setName(addUserBO.getName());
        user.setAge(addUserBO.getAge());
        user.setSex(addUserBO.getSex());
        user.setPwd(addUserBO.getPwd());

        RLock lock = redissonClient.getLock("lock");
        try {
            if (lock.isLocked()) {
                log.warn("已经被锁");
                return false;
            }
            lock.lock(30, TimeUnit.SECONDS); // 设置自动解锁
//            RAtomicLong count = redissonClient.getAtomicLong("count");
//            if (count.get() <= 0) {
//                log.warn("库存为0");
//                return false;
//            }
            this.usersRepository.saveAndFlush(user);
//            redissonClient.getBucket("user").set(user, Duration.ofMinutes(30));
            redissonClient.getMap("user-map").put(user.getName(), user);
            redissonClient.getList("user-list").add(user);
            stringRedisTemplate.opsForValue().set("aaa", System.currentTimeMillis() + "");
            redissonClient.getTopic("topic-add-user").publish(user);
            return true;
        } catch (Exception e) {
            log.error("addUser 异常", e);
            return false;
        } finally {
            lock.unlock();
        }
    }

    @Override
    public List<UserVO> getUser() {
        List<UserVO> res = new ArrayList<>();
        RList<Users> list = redissonClient.getList("user-list");
//        List<Users> list = usersRepository.findAll();
//        // 在这里删除 reids 内容
//        redissonClient.getMap("user").delete();
        if (list.isEmpty()) {
            return res;
        }
        for (Users user : list) {
            UserVO vo = new UserVO();
            vo.setAge(user.getAge());
            vo.setName(user.getName());
            vo.setSex(user.getSex());
            res.add(vo);
        }
        return res;
    }
    @Override
    public String login(LoginBO loginBO){
        Users user=this.usersRepository.getUsersByName(loginBO.getName());
        if (user==null){
            log.warn("登录失败，用户名不正确");
            return null;
        }
        if (!user.getPwd().equals(loginBO.getPwd())){
            log.warn("登录失败，密码不正确");
            return null;
        }
        String token = JwtUtil.generateToken(user.getName());
        redissonClient.getMapCache("auth").put(token,user,30,TimeUnit.MINUTES);
        log.info("["+user.getName()+"]登录成功，且加入缓存");
        redissonClient.getTopic("topic-login-user").publish(user);
        return "Bearer "+token;
    }
    public Boolean isAuth(String name){
        Object obj =redissonClient.getMapCache("auth").get(name);
        if (obj==null){
            log.info("["+name+"]没有登录");
            return false;
        }else {
            log.info("["+name+"]已登录");
            return true;
        }
    }

    @Override
    public Boolean logout(String token) {
        try {
            // 移除认证缓存中的token
            if (token != null && token.startsWith("Basic ")) {
                String actualToken = token.substring(6); // 去掉"Basic "前缀
                Object userObj = redissonClient.getMapCache("auth").remove(actualToken);

                if (userObj != null) {
                    Users user = (Users) userObj;
                    log.info("[" + user.getName() + "] 退出登录成功");

                    // 发布退出登录事件（可选）
                    redissonClient.getTopic("topic-logout-user").publish(user);
                    return true;
                } else {
                    log.warn("退出登录失败，token无效或已过期");
                    return false;
                }
            } else {
                log.warn("退出登录失败，token格式不正确");
                return false;
            }
        } catch (Exception e) {
            log.error("logout 异常", e);
            return false;
        }
    }
}